package com.jiyi.activity.datainput.jm;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.Spinner;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.jiyi.activity.datainput.DIBasePicActivity;
import com.jiyi.bean.datainput.DataInputBaseBean;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.inteface.DownloadPicOverInterface;
import com.jiyi.inteface.WebApi;
import com.jiyi.view.DateChooseDialog;
import com.jiyi.widget.picselect.PicSelectConstans;
import com.swift.base.ApplicationBase;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.CheckUtil;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class DataInputBaseActivity extends DIBasePicActivity implements
        DownloadPicOverInterface {

    /* 头部 */
    @BindView(R.id.tvBack)
    TextView tvBack;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvSearch)
    TextView tvSearch;

    @BindView(R.id.spBuildType)
    Spinner spBuildType;

    @BindView(R.id.etName)
    EditText etName;
    @BindView(R.id.etAdress)
    EditText etAdress;
    @BindView(R.id.etCreate)
    EditText etCreate;
    @BindView(R.id.etHeight)
    EditText etHeight;
    @BindView(R.id.etMianJi)
    EditText etMianJi;
    @BindView(R.id.etGLQK)
    EditText etGLQK;
    @BindView(R.id.etJLR)
    EditText etJLR;
    @BindView(R.id.etJLRTel)
    EditText etJLRTel;
    @BindView(R.id.spJSQK)
    Spinner spJSQK;
    @BindView(R.id.etCZQK)
    EditText etCZQK;
    @BindView(R.id.spBJXT)
    Spinner spBJXT;
    @BindView(R.id.spMHXT)
    Spinner spMHXT;
    @BindView(R.id.spJKXT)
    Spinner spJKXT;

    ArrayAdapter<String> stateBuildAdapter, stateJSQK, stateBJXT, stateMHXT,
            stateJKXT;

    Dialog dialog;
    String build_no;

    @BindView(R.id.gvPic)
    GridView gvPic;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_input_base);
        ButterKnife.bind(this);
        init();
    }

    @Override
    protected void onDestroy() {
        hideDialog(dialog);
        super.onDestroy();
    }

    public void init() {
        getIntentData();
        setTop();
        setViewStatus();
        setAdapter();
        if (!TextUtils.isEmpty(build_no)) {
            getData();
        }
        else
        {
            PicSelectConstans.publish_pics = new ArrayList<String>(){};
            refreshAdapter(gvPic);
        }
        super.setDownloadPicOverInterface(this);
    }

    private void getData() {
        Map<String, String> params = new HashMap<String, String>();
        params.put(AppConfig.ACCESS_TOKEN,
                UserInfoUtil.getCurrentUserAccessToken());
        params.put("build_info_id", build_no);

        dialog = showDialog(dialog);
        VolleyRequest.StringRequestPost(this, WebApi.DATA_INPUT_BASE_READ, "",
                params, new StringInterface(this) {

                    @Override
                    public void stringSuccess(String result) {
                        try {
                            JSONObject obj = new JSONObject(result);
                            String status = obj.getString("status");
                            String info = obj.getString("info");
                            if (status.equals("200")) {
                                String data = obj.getString("data");
                                Log.e("dfdsf   ", result);
                                DataInputBaseBean temp = new Gson().fromJson(
                                        data, DataInputBaseBean.class);
                                setData(temp);
                            } else if (status.equals("404")
                                    && info.contains("尚未登录")) {
                                ToastUtil.getInstances().showMsg(
                                        "尚未登录或该用户在其他地方登录，请重新登录！");
                                // 清除环信登录
                                UserHelp.getInstance().clearUser(
                                        ApplicationBase.Context, true);
                                return;
                            } else {
                                ToastUtil.getInstances().showMsg(info);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        } finally {
                            hideDialog(dialog);
                        }
                    }

                    @Override
                    public void stringError(VolleyError error) {
                        hideDialog(dialog);
                        ToastUtil.getInstances().showMsg(
                                R.string.err_http_response);
                    }
                });
    }

    private void getIntentData() {
        build_no = getIntent().getStringExtra("build_no");
    }

    private void setViewStatus() {
        // 设置日期控件不能输出
        etCreate.setKeyListener(null);

        // 设置必填项检测提示
        etName.setTag(R.id.tag_view_empty, "楼盘名称不能为空");
        etAdress.setTag(R.id.tag_view_empty, "楼盘地址不能为空");
    }

    private void setAdapter() {
        stateBuildAdapter = new ArrayAdapter<String>(this,
                R.layout.item_spinner, getResources().getStringArray(
                R.array.build_type));
        spBuildType.setAdapter(stateBuildAdapter);
        stateJSQK = new ArrayAdapter<String>(this, R.layout.item_spinner,
                getResources().getStringArray(R.array.build_qk));
        spJSQK.setAdapter(stateJSQK);
        stateBJXT = new ArrayAdapter<String>(this, R.layout.item_spinner,
                getResources().getStringArray(R.array.build_az));
        spBJXT.setAdapter(stateBJXT);
        stateMHXT = new ArrayAdapter<String>(this, R.layout.item_spinner,
                getResources().getStringArray(R.array.build_az));
        spMHXT.setAdapter(stateMHXT);
        stateJKXT = new ArrayAdapter<String>(this, R.layout.item_spinner,
                getResources().getStringArray(R.array.build_az));
        spJKXT.setAdapter(stateJKXT);
    }

    private void setTop() {
        tvTitle.setText("建筑基础属性");
        tvSearch.setCompoundDrawables(null, null, null, null);
        tvSearch.setText("保存");
    }

    @OnClick({R.id.etCreate, R.id.tvBack, R.id.tvSearch})
    public void onClick(View view) {
        DateChooseDialog.Builder builder;
        switch (view.getId()) {
            case R.id.tvBack:
                PicSelectConstans.publish_pics.clear();
                finish();
                break;
            case R.id.tvSearch:
                // 保存
                if (CheckUtil.checkEditText(etName, etAdress)) {
                    doPost();
                }
                break;
            case R.id.etCreate:
                // 生产日期
                builder = new DateChooseDialog.Builder(this, etCreate.getText()
                        .toString());
                builder.setTitle("选择日期");
                builder.setTextView(etCreate);
                builder.setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });

                builder.setNegativeButton("取消",
                        new android.content.DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                builder.create().show();
                break;

            default:
                break;
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        PicSelectConstans.publish_pics.clear();
    }

    private void doPost() {


        if (true) {
            toast("提示");
            return;
        }

        String url = "";
        Map<String, String> params = new HashMap<String, String>();
        params.put(AppConfig.ACCESS_TOKEN,
                UserInfoUtil.getCurrentUserAccessToken());
        params.put("name", etName.getText().toString());
        params.put("address", etAdress.getText().toString());
        params.put("type", spBuildType.getSelectedItemPosition() + "");
        params.put("year", etCreate.getText().toString());
        params.put("height", etHeight.getText().toString());
        params.put("area", etMianJi.getText().toString());
        params.put("manager", etJLR.getText().toString());
        params.put("manager_phone", etJLRTel.getText().toString());
        params.put("fire_control_room_status", spJSQK.getSelectedItemPosition()
                + "");
        params.put("property_management", etGLQK.getText().toString());
        params.put("watchkeeper_condition", etCZQK.getText().toString());
        params.put("auto_alarm_system", spBJXT.getSelectedItemPosition() + "");
        params.put("auto_water_system", spMHXT.getSelectedItemPosition() + "");
        params.put("ele_fire_mon_system", spJKXT.getSelectedItemPosition() + "");
        if (!TextUtils.isEmpty(build_no)) {
            params.put("build_info_id", build_no);
            url = WebApi.DATA_INPUT_JCSX_EDIT;
        } else {
            url = WebApi.DATA_INPUT_JCSX;
        }
        Log.e("params   ", params.toString());

        PostFormBuilder postForm = OkHttpUtils.post().url(url);
        postForm.params(params);
        // 图片数组
        int size = PicSelectConstans.publish_pics.size();
        File file;
        for (int i = 0; i < size; i++) {
            if (PicSelectConstans.publish_pics.get(i).contains("http")) {
                continue;
            }
            file = new File(PicSelectConstans.publish_pics.get(i));
            postForm.addFile("image[]", "pic" + (i + 1) + ".jpg", file);
        }

        dialog = showDialog(dialog);
        postForm.build().execute(new StringCallback() {

            @Override
            public void onError(Call arg0, Exception exception, int arg2) {
                hideDialog(dialog);
                ToastUtil.getInstances().showMsg(exception.getMessage());
            }

            @Override
            public void onResponse(String result, int arg1) {
                try {
                    JSONObject obj = new JSONObject(result);
                    String status = obj.getString("status");
                    String info = obj.getString("info");
                    if (status.equals("200")) {
                        String data = obj.getString("data");
                        ToastUtil.getInstances().showMsg(info);
                        Intent intent = new Intent();
                        intent.putExtra("build_no", data);
                        setResult(RESULT_OK, intent);
                        finish();
                    } else if (status.equals("404") && info.contains("尚未登录")) {
                        ToastUtil.getInstances().showMsg(
                                "尚未登录或该用户在其他地方登录，请重新登录！");
                        // 清除环信登录
                        UserHelp.getInstance().clearUser(ApplicationBase.Context,
                                true);
                        return;
                    } else {
                        ToastUtil.getInstances().showMsg(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } finally {
                    hideDialog(dialog);
                }
            }
        });
    }

    void setData(DataInputBaseBean dataInputBaseBean) {
        etName.setText(dataInputBaseBean.getName());
        etAdress.setText(dataInputBaseBean.getAddress());
        spBuildType.setSelection(dataInputBaseBean.getType());
        etCreate.setText(dataInputBaseBean.getYear());
        etHeight.setText(dataInputBaseBean.getHeight());
        etMianJi.setText(dataInputBaseBean.getArea());
        etGLQK.setText(dataInputBaseBean.getProperty_management());
        etJLR.setText(dataInputBaseBean.getManager());
        etJLRTel.setText(dataInputBaseBean.getManager_phone());
        spJSQK.setSelection(dataInputBaseBean.getFire_control_room_status());
        etCZQK.setText(dataInputBaseBean.getWatchkeeper_condition());
        spBJXT.setSelection(dataInputBaseBean.getAuto_alarm_system());
        spMHXT.setSelection(dataInputBaseBean.getAuto_water_system());
        spJKXT.setSelection(dataInputBaseBean.getEle_fire_mon_system());

        PicSelectConstans.publish_pics = dataInputBaseBean.getImage() == null ? new ArrayList<String>()
                : dataInputBaseBean.getImage();
        refreshAdapter(gvPic);
    }

    @Override
    public void post() {
        doPost();
    }

}
